<template>
  <div class="papers-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>试卷管理</span>
          <el-space>
            <el-button
              v-if="userStore.isAdmin || userStore.isTeacher"
              type="primary"
              @click="showManualDialog = true"
            >
              手动组卷
            </el-button>
            <el-button
              v-if="userStore.isAdmin || userStore.isTeacher"
              type="success"
              @click="showAutoDialog = true"
            >
              自动组卷
            </el-button>
          </el-space>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="80px">
        <el-form-item label="课程">
          <el-select
            v-model="queryForm.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            style="width: 200px"
            @change="handleQuery"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷名称">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入试卷名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>

      <!-- 试卷表格 -->
      <el-table
        v-loading="loading"
        :data="paperList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="试卷名称" min-width="200" />
        <el-table-column label="所属课程" width="150">
          <template #default="{ row }">
            {{ getCourseName(row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长(分钟)" width="120" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleView(row.id)"
            >
              查看
            </el-button>
            <el-button
              link
              type="success"
              size="small"
              @click="handleViewRecords(row.id)"
            >
              考试记录
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="warning"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="danger"
              size="small"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 手动组卷对话框 -->
    <el-dialog
      v-model="showManualDialog"
      :title="isEdit ? '编辑试卷' : '手动组卷'"
      width="1000px"
      @close="handleManualDialogClose"
    >
      <el-form
        ref="manualFormRef"
        :model="manualForm"
        :rules="manualFormRules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="manualForm.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="manualForm.courseId"
            placeholder="请选择所属课程"
            filterable
            style="width: 100%"
            @change="handleCourseChange"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input-number v-model="manualForm.duration" :min="1" :max="600" /> 分钟
        </el-form-item>
        <el-form-item label="选择题目">
          <el-button type="primary" @click="showQuestionSelector = true">选择题目</el-button>
          <div v-if="manualForm.selectedQuestions.length > 0" style="margin-top: 10px">
            <el-table :data="manualForm.selectedQuestions" border size="small" max-height="300">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column label="题型" width="100">
                <template #default="{ row }">
                  {{ getQuestionTypeText(row.type) }}
                </template>
              </el-table-column>
              <el-table-column prop="content" label="题干" min-width="200" show-overflow-tooltip />
              <el-table-column label="分值" width="120">
                <template #default="{ row, $index }">
                  <el-input-number
                    v-model="row.score"
                    :min="1"
                    :max="100"
                    @change="updateTotalScore"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row, $index }">
                  <el-button
                    link
                    type="danger"
                    @click="removeQuestion($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px; font-weight: bold">
              总分：{{ manualForm.totalScore }} 分
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showManualDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleManualSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 题目选择器对话框 -->
    <el-dialog
      v-model="showQuestionSelector"
      title="选择题目"
      width="1200px"
    >
      <el-form :inline="true" :model="questionQueryForm" class="search-form">
        <el-form-item label="题型">
          <el-select v-model="questionQueryForm.type" placeholder="请选择题型" clearable style="width: 120px">
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="judge" />
            <el-option label="填空题" value="fill" />
            <el-option label="主观题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="questionQueryForm.difficulty" placeholder="请选择难度" clearable style="width: 120px">
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadQuestions">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="questionLoading"
        :data="questionList"
        border
        max-height="400"
        @selection-change="handleQuestionSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="题型" width="100">
          <template #default="{ row }">
            {{ getQuestionTypeText(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="题干" min-width="250" show-overflow-tooltip />
        <el-table-column prop="score" label="基准分值" width="100" />
      </el-table>
      <template #footer>
        <el-button @click="showQuestionSelector = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectQuestions">确定</el-button>
      </template>
    </el-dialog>

    <!-- 自动组卷对话框 -->
    <el-dialog
      v-model="showAutoDialog"
      title="自动组卷"
      width="800px"
      @close="handleAutoDialogClose"
    >
      <el-form
        ref="autoFormRef"
        :model="autoForm"
        :rules="autoFormRules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="autoForm.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="autoForm.courseId"
            placeholder="请选择所属课程"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试时长" prop="duration">
          <el-input-number v-model="autoForm.duration" :min="1" :max="600" /> 分钟
        </el-form-item>
        <el-divider>组卷规则</el-divider>
        <el-form-item label="题型配置">
          <div v-for="(rule, type) in autoForm.typeRules" :key="type" style="margin-bottom: 10px">
            <el-checkbox v-model="rule.enabled">{{ getQuestionTypeText(type) }}</el-checkbox>
            <el-input-number
              v-if="rule.enabled"
              v-model="rule.count"
              :min="0"
              :max="100"
              style="width: 100px; margin-left: 10px"
            />
            题，每题
            <el-input-number
              v-if="rule.enabled"
              v-model="rule.score"
              :min="1"
              :max="100"
              style="width: 100px; margin-left: 10px"
            />
            分
          </div>
        </el-form-item>
        <el-form-item label="难度分布">
          <el-space>
            <span>简单：</span>
            <el-input-number v-model="autoForm.difficultyDistribution.easy" :min="0" :max="100" />%
            <span>中等：</span>
            <el-input-number v-model="autoForm.difficultyDistribution.medium" :min="0" :max="100" />%
            <span>困难：</span>
            <el-input-number v-model="autoForm.difficultyDistribution.hard" :min="0" :max="100" />%
          </el-space>
          <div style="margin-top: 10px; color: #999">
            合计：{{ autoForm.difficultyDistribution.easy + autoForm.difficultyDistribution.medium + autoForm.difficultyDistribution.hard }}%
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAutoDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleAutoSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看试卷详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="试卷详情"
      width="1000px"
    >
      <div v-if="viewPaper">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="试卷名称">{{ viewPaper.paper.name }}</el-descriptions-item>
          <el-descriptions-item label="所属课程">
            {{ getCourseName(viewPaper.paper.courseId) }}
          </el-descriptions-item>
          <el-descriptions-item label="考试时长">{{ viewPaper.paper.duration }} 分钟</el-descriptions-item>
        </el-descriptions>
        <el-divider>题目列表</el-divider>
        <el-table :data="viewPaper.questions" border max-height="400">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="题型" width="100">
            <template #default="{ row }">
              {{ getQuestionTypeText(row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="content" label="题干" min-width="250" show-overflow-tooltip />
          <el-table-column prop="score" label="分值" width="100" />
        </el-table>
        <div style="margin-top: 10px; font-weight: bold">
          总分：{{ viewPaper.questions.reduce((sum, q) => sum + q.score, 0) }} 分
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/user'
import {
  getPaperList,
  getPaperById,
  getMyPapers,
  createManualPaper,
  createAutoPaper,
  updatePaper,
  deletePaper,
  updatePaperQuestions,
  type PaperInfo,
  type PaperDetailResponse
} from '../../api/paper'
import { getMyCourses, getCourseList, type CourseInfo } from '../../api/course'
import { getQuestionList, type QuestionInfo } from '../../api/question'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const submitLoading = ref(false)
const questionLoading = ref(false)
const paperList = ref<PaperInfo[]>([])
const courseOptions = ref<CourseInfo[]>([])
const questionList = ref<QuestionInfo[]>([])
const selectedQuestions = ref<QuestionInfo[]>([])

const queryForm = reactive({
  name: '',
  courseId: null as number | null
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const showManualDialog = ref(false)
const showAutoDialog = ref(false)
const showQuestionSelector = ref(false)
const viewDialogVisible = ref(false)
const viewPaper = ref<PaperDetailResponse | null>(null)
const isEdit = ref(false)
const currentPaperId = ref<number | null>(null)

const manualFormRef = ref<FormInstance>()
const manualForm = reactive({
  name: '',
  courseId: null as number | null,
  duration: 120,
  selectedQuestions: [] as Array<QuestionInfo & { score: number }>,
  totalScore: 0
})

const autoFormRef = ref<FormInstance>()
const autoForm = reactive({
  name: '',
  courseId: null as number | null,
  duration: 120,
  typeRules: {
    single: { enabled: true, count: 5, score: 5 },
    multiple: { enabled: false, count: 3, score: 10 },
    judge: { enabled: false, count: 5, score: 3 },
    fill: { enabled: false, count: 3, score: 5 },
    essay: { enabled: false, count: 2, score: 15 }
  },
  difficultyDistribution: {
    easy: 30,
    medium: 50,
    hard: 20
  }
})

const questionQueryForm = reactive({
  type: '',
  difficulty: ''
})

const manualFormRules: FormRules = {
  name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择所属课程', trigger: 'change' }],
  duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }]
}

const autoFormRules: FormRules = {
  name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择所属课程', trigger: 'change' }],
  duration: [{ required: true, message: '请输入考试时长', trigger: 'blur' }]
}

// 获取课程名称
const getCourseName = (courseId: number) => {
  const course = courseOptions.value.find(c => c.id === courseId)
  return course ? course.name : '-'
}

// 获取题型文本
const getQuestionTypeText = (type: string) => {
  const map: { [key: string]: string } = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '主观题'
  }
  return map[type] || type
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 判断是否可以编辑
const canEdit = (row: PaperInfo) => {
  if (userStore.isAdmin) return true
  if (userStore.isTeacher) {
    const userId = parseInt(localStorage.getItem('userId') || '0')
    return row.teacherId === userId
  }
  return false
}

// 加载课程列表
const loadCourses = async () => {
  try {
    if (userStore.isAdmin) {
      const res = await getCourseList({ page: 1, size: 1000 })
      courseOptions.value = res.data.data || []
    } else if (userStore.isTeacher) {
      const res = await getMyCourses()
      courseOptions.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 获取试卷列表
const fetchPaperList = async () => {
  loading.value = true
  try {
    const queryParams = {
      name: queryForm.name || undefined,
      courseId: queryForm.courseId || undefined,
      page: pagination.page,
      size: pagination.size
    }

    const res = await getPaperList(queryParams)
    paperList.value = res.data.data || []
    pagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取试卷列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchPaperList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.courseId = null
  handleQuery()
}

// 分页改变
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchPaperList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchPaperList()
}

// 查看
const handleView = async (id: number) => {
  try {
    const res = await getPaperById(id)
    viewPaper.value = res.data
    viewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取试卷详情失败')
  }
}

// 编辑
const handleEdit = async (row: PaperInfo) => {
  try {
    // 获取试卷详情
    const res = await getPaperById(row.id)
    if (!res.data) {
      ElMessage.error('获取试卷详情失败')
      return
    }
    
    isEdit.value = true
    currentPaperId.value = row.id
    
    // 填充表单数据
    manualForm.name = res.data.paper.name
    manualForm.courseId = res.data.paper.courseId
    manualForm.duration = res.data.paper.duration
    // 填充题目数据
    manualForm.selectedQuestions = res.data.questions.map(q => ({
      id: q.id,
      type: q.type,
      content: q.content,
      options: q.options,
      answer: q.answer,
      analysis: q.analysis,
      difficulty: q.difficulty,
      score: q.score,
      courseId: row.courseId
    }))
    updateTotalScore()
    
    showManualDialog.value = true
  } catch (error) {
    ElMessage.error('获取试卷详情失败')
  }
}

// 查看考试记录
const handleViewRecords = (paperId: number) => {
  router.push({
    name: 'ExamRecords',
    params: { paperId: paperId.toString() }
  })
}

// 删除
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该试卷吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deletePaper(id)
    ElMessage.success('删除成功')
    fetchPaperList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 课程变化时加载题目
const handleCourseChange = () => {
  manualForm.selectedQuestions = []
  manualForm.totalScore = 0
}

// 加载题目列表
const loadQuestions = async () => {
  if (!manualForm.courseId) {
    ElMessage.warning('请先选择课程')
    return
  }

  questionLoading.value = true
  try {
    const res = await getQuestionList({
      courseId: manualForm.courseId,
      type: questionQueryForm.type || undefined,
      difficulty: questionQueryForm.difficulty || undefined,
      page: 1,
      size: 1000
    })
    questionList.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取题目列表失败')
  } finally {
    questionLoading.value = false
  }
}

// 题目选择变化
const handleQuestionSelectionChange = (selection: QuestionInfo[]) => {
  selectedQuestions.value = selection
}

// 确认选择题目
const confirmSelectQuestions = () => {
  const newQuestions = selectedQuestions.value.filter(q => {
    return !manualForm.selectedQuestions.some(sq => sq.id === q.id)
  })
  
  newQuestions.forEach(q => {
    manualForm.selectedQuestions.push({
      ...q,
      score: q.score || 5
    })
  })
  
  updateTotalScore()
  showQuestionSelector.value = false
  selectedQuestions.value = []
}

// 移除题目
const removeQuestion = (index: number) => {
  manualForm.selectedQuestions.splice(index, 1)
  updateTotalScore()
}

// 更新总分
const updateTotalScore = () => {
  manualForm.totalScore = manualForm.selectedQuestions.reduce((sum, q) => sum + (q.score || 0), 0)
}

// 手动组卷提交
const handleManualSubmit = async () => {
  if (!manualFormRef.value) return

  await manualFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    if (manualForm.selectedQuestions.length === 0) {
      ElMessage.warning('请至少选择一道题目')
      return
    }

    // 格式化日期时间
    const formatDateTime = (dateTimeStr: string) => {
      // 如果已经是ISO格式，直接返回
      if (dateTimeStr.includes('T')) {
        return dateTimeStr
      }
      // 否则转换为ISO格式
      return dateTimeStr.replace(' ', 'T')
    }

    submitLoading.value = true
    try {
      if (isEdit.value && currentPaperId.value) {
        // 获取原始试卷信息以保留状态
        const originalPaper = paperList.value.find(p => p.id === currentPaperId.value)
        // 更新试卷
        await updatePaper(currentPaperId.value, {
          id: currentPaperId.value,
          name: manualForm.name,
          courseId: manualForm.courseId!,
          duration: manualForm.duration,
          status: originalPaper?.status || 'draft', // 保留原有状态
          teacherId: 0 // 后端会忽略
        })
        
        // 更新试卷题目
        await updatePaperQuestions(currentPaperId.value, {
          questionIds: manualForm.selectedQuestions.map(q => q.id),
          scores: manualForm.selectedQuestions.map(q => q.score)
        })
        
        ElMessage.success('更新成功')
      } else {
        // 创建试卷
        await createManualPaper({
          paper: {
            name: manualForm.name,
            courseId: manualForm.courseId!,
            duration: manualForm.duration
          },
          questionIds: manualForm.selectedQuestions.map(q => q.id),
          scores: manualForm.selectedQuestions.map(q => q.score)
        })
        ElMessage.success('创建成功')
      }
      
      showManualDialog.value = false
      fetchPaperList()
    } catch (error) {
      // 错误已在拦截器中处理
    } finally {
      submitLoading.value = false
    }
  })
}

// 自动组卷提交
const handleAutoSubmit = async () => {
  if (!autoFormRef.value) return

  await autoFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    // 检查至少选择一种题型
    const enabledTypes = Object.entries(autoForm.typeRules).filter(([_, rule]) => rule.enabled)
    if (enabledTypes.length === 0) {
      ElMessage.warning('请至少选择一种题型')
      return
    }

    // 检查难度分布
    const totalPercent = autoForm.difficultyDistribution.easy +
                        autoForm.difficultyDistribution.medium +
                        autoForm.difficultyDistribution.hard
    if (Math.abs(totalPercent - 100) > 1) {
      ElMessage.warning('难度分布百分比之和应为100%')
      return
    }

    // 格式化日期时间
    const formatDateTime = (dateTimeStr: string) => {
      // 如果已经是ISO格式，直接返回
      if (dateTimeStr.includes('T')) {
        return dateTimeStr
      }
      // 否则转换为ISO格式
      return dateTimeStr.replace(' ', 'T')
    }

    submitLoading.value = true
    try {
      const typeRules: { [key: string]: { count: number; score: number } } = {}
      enabledTypes.forEach(([type, rule]) => {
        typeRules[type] = {
          count: rule.count,
          score: rule.score
        }
      })

      await createAutoPaper({
        paper: {
          name: autoForm.name,
          courseId: autoForm.courseId!,
          duration: autoForm.duration
        },
        rule: {
          typeRules,
          difficultyDistribution: autoForm.difficultyDistribution
        }
      })
      ElMessage.success('创建成功')
      showAutoDialog.value = false
      fetchPaperList()
    } catch (error) {
      // 错误已在拦截器中处理
    } finally {
      submitLoading.value = false
    }
  })
}

// 关闭手动组卷对话框
const handleManualDialogClose = () => {
  manualFormRef.value?.resetFields()
  manualForm.selectedQuestions = []
  manualForm.totalScore = 0
  isEdit.value = false
  currentPaperId.value = null
  manualForm.name = ''
  manualForm.courseId = null
  manualForm.duration = 120
}

// 关闭自动组卷对话框
const handleAutoDialogClose = () => {
  autoFormRef.value?.resetFields()
  autoForm.typeRules = {
    single: { enabled: true, count: 5, score: 5 },
    multiple: { enabled: false, count: 3, score: 10 },
    judge: { enabled: false, count: 5, score: 3 },
    fill: { enabled: false, count: 3, score: 5 },
    essay: { enabled: false, count: 2, score: 15 }
  }
  autoForm.difficultyDistribution = {
    easy: 30,
    medium: 50,
    hard: 20
  }
}

// 监听课程选择对话框显示
watch(showQuestionSelector, (newVal) => {
  if (newVal && manualForm.courseId) {
    loadQuestions()
  }
})

onMounted(async () => {
  await loadCourses()
  fetchPaperList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

